import ma.const
import ma.utils.location
from ma.utils.clustersetup import CLUSTER_IPS

import os
import os.path
import sys
import getopt
import time

ma_stats_filename = 'ma_stats.csv'
log_filename = 'ma_logger.log'
master_log_filename = 'ma_master.log'
estimator_filename = 'estimator_stats.csv'
threshold_filename = 'threshold_stats.csv'
nohup_out_filename = 'nohup.out'
nohup_master_out_filename = 'nohup_master.out'

nohup_exec_path = 'nohup'
python_exec_path = ma.const.XmlData.get_filepath_str_data(ma.const.xml_python_exec)
mr_exec_path = os.path.join(ma.utils.location.get_mr_path(), 'core', 'nodetracker.py')
master_exec_path = os.path.join(ma.utils.location.get_mr_path(), 'core', 'master.py')
mr_remote_exec_path = os.path.join(ma.utils.location.get_scripts_path(), 'runscriptmr.py')

#print "Starting dstat"
#os.system(dstat_path + ' -T -cn -C total -N eth0 --nocolor --output ' + vital_stats_filename + ' &>/dev/null &')

master_cmd = python_exec_path + ' ' + master_exec_path
nodetracker_cmd = python_exec_path + ' ' + mr_exec_path 
remote_cmd = python_exec_path + ' ' + mr_remote_exec_path + ' -s'


optlist, args = getopt.getopt(sys.argv[1:], 'rmns')
start_master = False
start_remote = False
start_on_nohup = False
silent_mode = False
for opt in optlist:
    if opt[0] == '-r':
        start_remote = True
    elif opt[0] == '-m':
        start_master = True
    elif opt[0] == '-n':
        start_on_nohup = True
    elif opt[0] == '-s':
        silent_mode = True
        
# if arguments coming in args
if len(args) > 0:
    for arg in args:
        if arg == '-r':
            start_remote = True
        elif arg == '-m':
            start_master = True
        elif arg == '-n':
            start_on_nohup = True
        elif arg == '-s':
            silent_mode = True
        elif arg.isdigit():
            forced_job_id = int(arg)
            
            if not silent_mode: print('deleting local temp dirs')
            local_fs_input_path = ma.const.JobsXmlData.get_filepath_str_data(ma.const.xml_local_input_temp_dir, forced_job_id)
            local_fs_output_path = ma.const.JobsXmlData.get_filepath_str_data(ma.const.xml_local_output_temp_dir, forced_job_id)
            local_fs_compute_path = ma.const.JobsXmlData.get_filepath_str_data(ma.const.xml_local_compute_temp_dir, forced_job_id)
            os.system('find ' + local_fs_input_path + ' -type f -name \'*\' | xargs rm -rf')
            os.system('find ' + local_fs_output_path + ' -type f -name \'*\' | xargs rm -rf')
            os.system('find ' + local_fs_compute_path + ' -type f -name \'*\' | xargs rm -rf')
                        
            if not silent_mode: print('Forcing job-id', forced_job_id)
            
            # add the job id to the master's command
            master_cmd = master_cmd + ' ' + str(forced_job_id)
            remote_cmd = remote_cmd + ' ' + str(forced_job_id)


if not silent_mode: print('usage: python runscriptmr.py [-r to start on all remote machines] [-m to start machine on current node] [-n use nohup] [-s for silent mode] [job_id]')

if not silent_mode: print("Deleting log files")
os.system('rm -f ' + ma_stats_filename)
os.system('rm -f ' + log_filename)
os.system('rm -f ' + master_log_filename)
os.system('rm -f ' + estimator_filename)
os.system('rm -f ' + threshold_filename)
os.system('rm -f ' + nohup_out_filename)
os.system('rm -f ' + nohup_master_out_filename)


# if this needs to be started immune to hangups
if start_on_nohup:
    master_cmd = nohup_exec_path + ' ' + master_cmd + ' > ' + nohup_master_out_filename
    nodetracker_cmd = nohup_exec_path + ' ' + nodetracker_cmd + ' > ' + nohup_out_filename
    remote_cmd = remote_cmd + ' -n'
elif silent_mode:
    master_cmd = master_cmd + ' > ' + nohup_master_out_filename
    nodetracker_cmd = nodetracker_cmd + ' > ' + nohup_out_filename

# starting master
if start_master:
    if not silent_mode: print("\\\\ --- Starting MR Master --- //")
    if not silent_mode: print("Executing ->", master_cmd)
    os.system(master_cmd + ' &')

if start_master and start_on_nohup and not silent_mode:
    os.system('tail -f ' + nohup_master_out_filename + ' &')

# starting remote servers
if start_remote:
    for ip in CLUSTER_IPS:
        os.system('ssh ' + ip + ' \'' + remote_cmd + '\' &')
        if not silent_mode: print("Started MR NT at " + ip)

if not silent_mode: print("Sleeping for 20 secs - waiting for Master to initialize")
time.sleep(20)

# starting nodetracker
if not silent_mode: print("\\\\ --- Starting MR NT --- //")
if not silent_mode: print("Executing ->", nodetracker_cmd)
os.system(nodetracker_cmd + ' &')

time.sleep(2)

if start_on_nohup and not silent_mode:
    os.system('tail -f ' + nohup_out_filename)
